import { observable, action, computed, makeObservable, configure, runInAction } from 'mobx';
configure({ enforceActions: 'observed'});
class StoreApp {

    constructor() {
        makeObservable(this)
    }

    @observable list = [];
    @observable appleId = 0;

    @action.bound async addApple () {
        setTimeout(() => {
            // 异步1秒添加新苹果 id 为当前所有苹果数量，重量随机
            runInAction(() => {
                this.list.push({
                    name: '红苹果',
                    id: this.appleId++,
                    weight: Math.floor((Math.random() * 50)) + 200,
                    beEaten: false
                })
            })
        }, 500);
    }
    
    @action eatApple = (id) => {
        const apple = this.list.find(apple => apple.id === id);
        apple.beEaten = true;
    }
    @computed get appleList () {
        return this.list.filter(apple => apple.beEaten === false);
    }
    @computed get eatAppleList () {
        return this.list.filter(apple => apple.beEaten === true);
    }
    @computed get currentWeight () {
        return this.appleList.reduce((total,item)=> total += item.weight, 0);
    }
    @computed get eatWeight () {
        return this.eatAppleList.reduce((total,item)=> total += item.weight, 0);
    }
};

const appStore = new StoreApp();

export default appStore;
